//
//  NewPlanRecommendView.m
//  WanCaiC8
//
//  Created by 罗先森 on 2018/8/28.
//  Copyright © 2018年 tangang. All rights reserved.
//


#import "NewPlanRecommendView.h"
#import "PlanRecommendCell.h"
#import "PlanRecommendTopCell.h"

#import "PlanRecommendHeadView.h"
#import "PlanVM.h"
#import "InformationVM.h"
#import "MJRefresh.h"

#import "AdvertisingView.h"
#import "TGAdvertTableViewCell.h"

@interface NewPlanRecommendView()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic ,strong) PlanRecommendHeadView *headView;
@property (nonatomic ,strong) UICollectionView *numCollectionView;
@property (nonatomic ,strong) UICollectionView *typeCollectionView;
@property (nonatomic ,strong) NSMutableArray   *dataArr;
@property (nonatomic ,strong) NSMutableArray   *advertisingArr;
@property (nonatomic ,assign) NSInteger   page;



@property (nonatomic ,strong) NSMutableArray   *arr1;
@property (nonatomic ,strong) NSMutableArray   *arr2;
@property (nonatomic ,strong) NSMutableArray   *colArr1;
@property (nonatomic ,strong) NSMutableArray   *colArr2;
@property (nonatomic ,strong) AdvertisingView   *oneAdvertisingView;



@end

@implementation NewPlanRecommendView{
    LotteryNumType numType;
    dispatch_source_t _timer;
}


#pragma mark - 启动定时器
- (void)startTimer{
    
    WS(weakSelf);
    [self cancleTimer];
    
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    _timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(_timer,dispatch_walltime(NULL, 0),20.0*NSEC_PER_SEC, 0);
    
    dispatch_source_set_event_handler(_timer, ^{
        //
        weakSelf.page=1;

        [weakSelf loadData];
        
    });
    
    dispatch_async(dispatch_get_main_queue(), ^{
        NSLog(@"----正在刷新tableView");
        
        [weakSelf reloadData];
    });
    
    
    dispatch_resume(_timer);
}




- (instancetype)init{
    if (self=[super init]) {
        self.delegate=self;
        self.dataSource=self;
        
//        self.pageSize = 1;
        self.separatorStyle=UITableViewCellSeparatorStyleNone;
        [self registerClass:[PlanRecommendTopCell class] forCellReuseIdentifier:@"PlanRecommendTopCell"];
        self.rowHeight=UITableViewAutomaticDimension;
        self.estimatedRowHeight=50;
        [self registerClass:[PlanRecommendCell class] forCellReuseIdentifier:@"PlanRecommendCell"];
        [self registerClass:[TGAdvertTableViewCell class] forCellReuseIdentifier:@"TGAdvertTableViewCell"];
        WS(weakSelf);
        self.header=[MJRefreshNormalHeader headerWithRefreshingBlock:^{
            weakSelf.page=1;
//            [weakSelf.dataArr removeAllObjects];
//            [weakSelf reloadData];
            [weakSelf loadData];
        }];
        self.footer=[MJRefreshBackNormalFooter footerWithRefreshingBlock:^{
            [weakSelf loadData];
        }];
        [self reloadData];
        
        [self startTimer];
        
    }
    return self;
}

- (void)setLotteryModel:(LotteryTypeModel *)lotteryModel{
    _lotteryModel=lotteryModel;
    numType=[[BaseVM manage] getType:[self.lotteryModel.lType integerValue]];
    [self.headView cancleTimer];
    [self.headView removeFromSuperview];
    self.headView=nil;
    self.tableHeaderView=self.headView;
}

- (void)setPageSize:(NSInteger)pageSize{
    _pageSize=pageSize;
    self.page=1;
    [self.header beginRefreshing];

}

- (void)setIsNew:(BOOL)isNew{
    _isNew=isNew;
    self.headView.isNew=isNew;

    self.headView.frame=CGRectMake(0, 0, SCREEN_WIDTH, real_size(75));
    

    self.tableHeaderView=self.headView;
    [self reloadData];
    [self getAdvertising];
}

#pragma mark -- 获取广告
- (void)getAdvertising{
    WS(weakSelf);
    NSInteger type=10;
    if (_isNew) {
        type=11;
    }
    if ([BaseVM manage].city.length>0) {
        [[InformationVM manage] getAdvertWithLocation:@"0" andType:type Success:^(id returnValue) {
            weakSelf.advertisingArr=returnValue;
            if (weakSelf.isNew) {
                [weakSelf addAdvertisin];
            }
            [weakSelf reloadData];
        } andFail:^(NSString *errorMessage, NSError *error) {
            
        }];
    }
}

- (void)addAdvertisin{
    
    self.arr1 = [NSMutableArray array];
    self.arr2 = [NSMutableArray array];
    self.colArr1 = [NSMutableArray array];
    self.colArr2 = [NSMutableArray array];

    for (AdvertisingModel *model in self.advertisingArr) {
        if (model.Layer==1) {
            [self.arr1 addObject:model];
            if (model.IsDisplay) {
                [self.colArr1 addObject:model];
            }
        }
        if (model.Layer==2) {
            [self.arr2 addObject:model];
            if (model.IsDisplay) {
                [self.colArr2 addObject:model];
            }
        }
    }
    
     self.headView.frame=CGRectMake(0, 0, SCREEN_WIDTH, real_size(75 +self.arr1.count*40-40*ceil(self.colArr1.count/2.0)));

    
    [self.headView setModelArr:self.arr1 AndRowCount:(NSInteger)(self.arr1.count-ceil(self.colArr1.count/2.0))];
    self.tableHeaderView=self.headView;

}

- (void)loadData{
    WS(weakSelf);
    [[PlanVM manage] getPlanDataWithLtype:[self.lotteryModel.lType integerValue] andPageIndex:weakSelf.page andPageSize:self.pageSize Success:^(id returnValue) {
        [weakSelf.header endRefreshing];
        weakSelf.page+=1;
        NSArray *arr=returnValue;
        if (arr.count<weakSelf.pageSize) {
            [weakSelf.footer noticeNoMoreData];
        }else{
            [weakSelf.footer endRefreshing];
        }
        [weakSelf createData:returnValue];
//        [weakSelf reloadData];
    } andFail:^(NSString *errorMessage, NSError *error) {
        [weakSelf.header endRefreshing];
        [weakSelf.footer endRefreshing];
    }];
}

- (void)cancleTimer{
    [self.headView cancleTimer];
}

- (void)createData:(NSMutableArray *)arr{
    
    [self.dataArr removeAllObjects];
    for (PlanRecommendModel *model in arr) {
        if ([model.ShowSort isEqualToString:@"龙虎"]) {
            continue;
        }
        ///六彩
        if ([[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeLottery) {
            if ([model.ShowSort isEqualToString:@"特尾大小"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"特尾大小"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"特合单双"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"四肖中特"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"十码中特"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"六不中"]) {
                continue;
            }
        }
        ///双色球
        if ([[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeChromosphere) {
            if ([model.ShowSort isEqualToString:@"红2胆"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"蓝5码"]) {
                continue;
            }
        }
        ///福彩3D和排三
        if ([[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeLottery3D||[[BaseVM manage] getType:[self.lotteryModel.lType integerValue]]==LotteryNumTypeArrangement3) {
            if ([model.ShowSort isEqualToString:@"杀一码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"杀二码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"胆一码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"胆二码"]) {
                continue;
            }else if ([model.ShowSort isEqualToString:@"胆三码"]) {
                continue;
            }
        }
        
            if (model.OpenNum.length<=0) {
              
                    self.recommendModel=[[RecommendModel alloc]init];
                    self.recommendModel.OpenTime=model.OpenTime;
                    self.recommendModel.Issue=model.Issue;
                    self.recommendModel.OpenNum=model.OpenNum;
                    self.recommendModel.OpenNumAlias=model.OpenNumAlias;
                    self.recommendModel.lType=model.lType;
                    self.recommendModel.name = self.lotteryModel.Name;
                    [self.recommendModel.arr addObject:model];
                    [self.dataArr addObject:model];

            }
    }
    
    dispatch_async(dispatch_get_main_queue(), ^{
        [self reloadData];

    });

}

#pragma mark -- UITableViewDelegate ,UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.dataArr.count== 0) {
        return 0;
    } else {
        return self.dataArr.count+1+self.arr2.count;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return 5;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    UIView *view=[[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 5)];
    view.backgroundColor=DEFAULTBGCOLOR;
    return view;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
  
    
    if (indexPath.row==0) {
        PlanRecommendTopCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PlanRecommendTopCell" forIndexPath:indexPath];
        PlanRecommendModel *model=self.recommendModel.arr.lastObject;
        cell.count=[model.Num componentsSeparatedByString:@"|"].count+1.0;
        cell.model=self.recommendModel;
        cell.isNew=self.isNew;
        return cell;
    }else if(indexPath.row-1<self.dataArr.count){
        PlanRecommendCell *cell=[tableView dequeueReusableCellWithIdentifier:@"PlanRecommendCell" forIndexPath:indexPath];
        cell.row=indexPath.row-1;
        cell.model=self.dataArr[indexPath.row-1];
        cell.isNew=self.isNew;
        if (indexPath.row%2==0) {
            [cell setBgColor:[UIColor whiteColor]];
            
        }else{
            [cell setBgColor:DEFAULTBGCOLOR];
            
        }
        return cell;
    }else{
        
        TGAdvertTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"TGAdvertTableViewCell" forIndexPath:indexPath];
        [cell setAdModelArr:self.arr2 AndRowCount:(NSInteger)(self.arr2.count-ceil(self.colArr2.count/2.0))];
        return cell;
        
    }

}

- (NSMutableArray *)dataArr{
    if (!_dataArr) {
        _dataArr =[[NSMutableArray alloc]init];
    }
    return _dataArr;
}

- (PlanRecommendHeadView *)headView{
    if (!_headView) {
        _headView=[[PlanRecommendHeadView alloc]initWithType:numType];
        _headView.lType=self.lotteryModel.lType;
        _headView.lookNewBlock = self.lookeMore;
    }
    return _headView;
}

-(void)dealloc{
    NSLog(@"newplan--->dealloc");
    
}

- (AdvertisingView *)oneAdvertisingView{
    if (!_oneAdvertisingView) {
        WS(weakSelf);
        _oneAdvertisingView =[[AdvertisingView alloc]init];
        self.oneAdvertisingView.changeHeight = ^(float height) {
            [weakSelf.oneAdvertisingView mas_updateConstraints:^(MASConstraintMaker *make) {
                make.height.mas_equalTo(@(height));
            }];
        };
    }
    return _oneAdvertisingView;
}

-(void)adCellClickWithAdvertisingModel:(AdvertisingModel *)adModel{
    
    if ([adModel.Title containsString:@"】"]) {
        UIPasteboard *copy = [UIPasteboard generalPasteboard];
        NSRange startRange = [adModel.Title rangeOfString:@"【"];
        NSRange endRange = [adModel.Title rangeOfString:@"】"];
        NSRange range = NSMakeRange(startRange.location + startRange.length, endRange.location - startRange.location - startRange.length);
        NSString *result = [adModel.Title substringWithRange:range];
        
        [copy setString:result];
        
        [SVProgressHUD showSuccessWithStatus:@"复制成功"];
        
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            
            [SVProgressHUD dismiss];
            [[UIApplication sharedApplication]openURL:[NSURL URLWithString: @"weixin://"]];
            
        });
        
    }else{
        if (adModel.TransferUrl.length<1) {return;}
        [[UIApplication sharedApplication]openURL:[NSURL URLWithString:adModel.TransferUrl]];
    }
}

@end
